package priv.bruce.service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import priv.bruce.entry.MovieComment;
import priv.bruce.entry.MovieInfo;
import priv.bruce.entry.UserInfo;
import priv.bruce.util.HandlerSet;
import priv.bruce.util.JDBCUtil;

public class SelectCommentsByUsernameService implements HandlerSet<MovieComment>{

	public Map<String, Object> findCommentByUsername(String username) throws Exception {
		String sql4Comment = "select * from t_comment as c "
				+ "join t_user as u on c.user_id=u.user_id where u.user_name like CONCAT('%',?,'%') "
				+ "order by comment_time DESC";
		Map<String, Object> map = new HashMap<>();
		List<MovieComment> movieComments = JDBCUtil.query(sql4Comment,this,username);
		map.put("commentInfo", movieComments);
		String sql4Username = "select * from t_user as u join t_comment as c"
				+ " on u.user_id=c.user_id where u.user_name like CONCAT('%',?,'%') order by c.comment_time DESC";
		List<UserInfo> userInfo = JDBCUtil.query(sql4Username, new HandlerSet<UserInfo>() {
			@Override
			public UserInfo handler(ResultSet rs) throws SQLException {
				UserInfo userInfo = new UserInfo();
				userInfo.setUser_id(rs.getInt("user_id"));
				userInfo.setUser_name(rs.getString("user_name"));
				userInfo.setPassword(rs.getString("password"));
				userInfo.setUser_phone(rs.getString("user_phone"));
				userInfo.setUser_addr(rs.getString("user_addr"));
				userInfo.setUser_mail(rs.getString("user_mail"));
				userInfo.setUser_enable(rs.getInt("user_enable"));
				userInfo.setQuanxian(rs.getInt("quanxian"));
				return userInfo;
			}
		},username);
		map.put("userInfo", userInfo);
		String sql4Moviename = "select movie_name from t_comment as c join t_movie as m "
				+ "join t_user as u on m.movie_id=c.movie_id and u.user_id=c.user_id"
				+ " where u.user_name like CONCAT('%',?,'%') order by c.comment_time DESC";
		List<MovieInfo> movieInfo = JDBCUtil.query(sql4Moviename, new HandlerSet<MovieInfo>() {
			@Override
			public MovieInfo handler(ResultSet rs) throws SQLException {
				MovieInfo movieInfo = new MovieInfo();
				movieInfo.setMovie_name(rs.getString("movie_name"));
				return movieInfo;
			}
		},username);
		map.put("movieInfo", movieInfo);
		return map;
	}
	@Override
	public MovieComment handler(ResultSet rs) throws SQLException {
		MovieComment comment = new MovieComment();
		comment.setComment_content(rs.getString("comment_content"));
		comment.setComment_time(rs.getTimestamp("comment_time"));
		comment.setComment_id(rs.getInt("comment_id"));
		return comment;
	}
}
